import axios from 'axios';
import Cookies from 'js-cookie';
import { showFailToast, closeToast } from 'vant';
import qs from 'qs';
import router from '@/router/index';

// 封装axios
export function request(config) {
    // 创建axios实例
    const instance = axios.create({
        // 基础请求url
        baseURL: 'http://10.248.123.135:8008/api',
        // 请求头参数
        headers: {
            'X-Requested-with': 'XMLHttpRequest',
            'Content-type': 'application/json;charset=utf-8',
        },
        // 表示跨域请求时是否需要使用凭证
        withCredentials: true,
        // 设置请求超时时间
        timeout: 5000,
        // 请求序列化
        paramsSerializer: {
            serialize: function (params) {
                return qs.stringify(params, { arrayFormat: 'brackets' });
            }
        },
    });
    // 添加请求响应拦截器
    // 请求拦截器
    instance.interceptors.request.use(
        (config) => {
            if (Cookies.get('Token')) {
                config.headers['Authorization'] = 'Bearer ' + Cookies.get('Token');
            }
            config.headers['Content-Type'] = 'application/json;charset=utf-8';
            return config;
        },
        (error) => {
            return Promise.reject(error);
        }
    );

    instance.interceptors.response.use(
        (response) => {
            closeToast();
            const res = response.data;
            if (res.status && res.status !== 200) {
                // 登录超时，重新登录
                if (res.status === '401') {
                    router.push({ path: "/login" });
                    Cookies.set('Token', "", -1);
                    sessionStorage.clear();
                }
                if (res.msg !== "非法访问") {
                    showFailToast(res.msg);
                }
                if (res.status === '500') {
                    router.push('/nullPage');
                }
                return Promise.reject(res || 'error');
            } else {
                return Promise.resolve(res);
            }
        },
        (err) => {
            closeToast();
            console.log('err' + err);
            return Promise.reject(err);
        }
    );

    return instance(config);
}
export const imgUrls = 'http://10.248.123.135:8008/api';